package com.xyoto.community.service.impl;

import com.xyoto.community.cache.CacheInstruction;
import com.xyoto.community.entity.main.AnonymousUser;
import com.xyoto.community.mapper.main.AnonyUserMapper;
import com.xyoto.community.service.AnonymousCacheService;
import com.xyoto.community.utils.RedisCommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author coderFu
 * @create 2021/11/14
 */
@Service
public class AnonymousCacheServiceImpl implements AnonymousCacheService {

    @Autowired
    private AnonyUserMapper anonyUserMapper;

    @Autowired
    private RedisCommonUtils redisCommonUtils;

    @Override
    public List<AnonymousUser> getAnonymousListFromCache() {
        //从缓存中获取数据
        Map<Object, Object> anonymousUser = redisCommonUtils.hmget(CacheInstruction.ANONYMOUS_USER);
        //判断是否存在数据
        if (anonymousUser.size() == 0 ){
            //更新缓存信息
            //查询数据库
            List<AnonymousUser> anonymousUserList = anonyUserMapper.getAnonymousUserList();
            //存储到缓存中
            for (AnonymousUser anonymousUser1 : anonymousUserList) {
                redisCommonUtils.hset(CacheInstruction.ANONYMOUS_USER,anonymousUser1.getId(),anonymousUser1);
            }
            //返回缓存中的匿名信息列表
            return anonymousUserList;
        }
        List<AnonymousUser> anonymousUserList = new ArrayList<>();
        anonymousUser.forEach((a,b)->{
            anonymousUserList.add((AnonymousUser) b);
        });
        return anonymousUserList;
    }

    @Override
    public synchronized AnonymousUser updateAnonymousCacheList(Integer id) {
        Object anonymousUserObj = redisCommonUtils.hget(CacheInstruction.ANONYMOUS_USER, id);
        if (anonymousUserObj != null){
            return (AnonymousUser)anonymousUserObj;
        }
        //查询数据库
        AnonymousUser anonymousUser = anonyUserMapper.getAnonymousById(id);
        //判断是否为null
        if (anonymousUser == null){
            return null;
        }
        //添加到缓存中
        redisCommonUtils.hset(CacheInstruction.ANONYMOUS_USER,anonymousUser.getId(),anonymousUser);
        return anonymousUser;
    }


}
